
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>事件循环 &#8212; Python 3.7.3 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.3 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="Futures" href="asyncio-future.html" />
    <link rel="prev" title="异常" href="asyncio-exceptions.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/asyncio-eventloop.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/switchers.js"></script>
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="asyncio-future.html" title="Futures"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="asyncio-exceptions.html" title="异常"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">zh_CN</span>
          <span class="version_switcher_placeholder">3.7.3</span>
          <a href="../index.html">文档</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >网络和进程间通信</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="asyncio.html" accesskey="U"><code class="docutils literal notranslate"><span class="pre">asyncio</span></code> --- 异步 I/O</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="event-loop">
<h1>事件循环<a class="headerlink" href="#event-loop" title="永久链接至标题">¶</a></h1>
<p class="rubric">前言</p>
<p>事件循环是每个 asyncio 应用的核心。 事件循环会运行异步任务和回调，执行网络 IO 操作，以及运行子进程。</p>
<p>应用开发者通常应当使用高层级的 asyncio 函数，例如 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a>，应当很少有必要引用循环对象或调用其方法。 本节所针对的主要是低层级代码、库和框架的编写者，他们需要更细致地控制事件循环行为。</p>
<p class="rubric">获取事件循环</p>
<p>以下低层级函数可被用于获取、设置或创建事件循环:</p>
<dl class="function">
<dt id="asyncio.get_running_loop">
<code class="descclassname">asyncio.</code><code class="descname">get_running_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.get_running_loop" title="永久链接至目标">¶</a></dt>
<dd><p>返回当前 OS 线程中正在运行的事件循环。</p>
<p>如果没有正在运行的事件循环则会引发 <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>。 此函数只能由协程或回调来调用。</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.get_event_loop">
<code class="descclassname">asyncio.</code><code class="descname">get_event_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.get_event_loop" title="永久链接至目标">¶</a></dt>
<dd><p>获取当前事件循环。 如果当前 OS 线程没有设置当前事件循环并且 <a class="reference internal" href="#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_event_loop()</span></code></a> 还没有被调用，asyncio 将创建一个新的事件循环并将其设置为当前循环。</p>
<p>由于此函数具有相当复杂的行为（特别是在使用了自定义事件循环策略的时候），更推荐在协程和回调中使用 <a class="reference internal" href="#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a> 函数而非 <a class="reference internal" href="#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop()</span></code></a>。</p>
<p>应该考虑使用 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> 函数而非使用低层级函数来手动创建和关闭事件循环。</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.set_event_loop">
<code class="descclassname">asyncio.</code><code class="descname">set_event_loop</code><span class="sig-paren">(</span><em>loop</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.set_event_loop" title="永久链接至目标">¶</a></dt>
<dd><p>将 <em>loop</em> 设置为当前 OS 线程的当前事件循环。</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.new_event_loop">
<code class="descclassname">asyncio.</code><code class="descname">new_event_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.new_event_loop" title="永久链接至目标">¶</a></dt>
<dd><p>创建一个新的事件循环。</p>
</dd></dl>

<p>请注意 <a class="reference internal" href="#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop()</span></code></a>, <a class="reference internal" href="#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_event_loop()</span></code></a> 以及 <a class="reference internal" href="#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">new_event_loop()</span></code></a> 函数的行为可以通过 <a class="reference internal" href="asyncio-policy.html#asyncio-policies"><span class="std std-ref">设置自定义事件循环策略</span></a> 来改变。</p>
<p class="rubric">内容</p>
<p>本文档包含下列小节:</p>
<ul class="simple">
<li>The <a class="reference internal" href="#event-loop-methods">Event Loop Methods</a> section is the reference documentation of
the event loop APIs;</li>
<li>The <a class="reference internal" href="#callback-handles">Callback Handles</a> section documents the <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code class="xref py py-class docutils literal notranslate"><span class="pre">Handle</span></code></a> and
<a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimerHandle</span></code></a> instances which are returned from scheduling
methods such as <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a> and <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_later()</span></code></a>;</li>
<li>The <a class="reference internal" href="#server-objects">Server Objects</a> section documents types returned from
event loop methods like <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a>;</li>
<li>The <a class="reference internal" href="#event-loop-implementations">Event Loop Implementations</a> section documents the
<a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> and <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> classes;</li>
<li><a class="reference internal" href="#examples">Examples</a> section 展示了如何使用某些事件循环API。</li>
</ul>
<div class="section" id="event-loop-methods">
<span id="asyncio-event-loop"></span><h2>事件循环方法集<a class="headerlink" href="#event-loop-methods" title="永久链接至标题">¶</a></h2>
<p>Event loops have <strong>low-level</strong> APIs for the following:</p>
<div class="contents local topic" id="id1">
<ul class="simple">
<li><a class="reference internal" href="#running-and-stopping-the-loop" id="id2">Running and stopping the loop</a></li>
<li><a class="reference internal" href="#scheduling-callbacks" id="id3">Scheduling callbacks</a></li>
<li><a class="reference internal" href="#scheduling-delayed-callbacks" id="id4">Scheduling delayed callbacks</a></li>
<li><a class="reference internal" href="#creating-futures-and-tasks" id="id5">Creating Futures and Tasks</a></li>
<li><a class="reference internal" href="#opening-network-connections" id="id6">Opening network connections</a></li>
<li><a class="reference internal" href="#creating-network-servers" id="id7">Creating network servers</a></li>
<li><a class="reference internal" href="#transferring-files" id="id8">传输文件</a></li>
<li><a class="reference internal" href="#tls-upgrade" id="id9">TLS 升级</a></li>
<li><a class="reference internal" href="#watching-file-descriptors" id="id10">Watching file descriptors</a></li>
<li><a class="reference internal" href="#working-with-socket-objects-directly" id="id11">Working with socket objects directly</a></li>
<li><a class="reference internal" href="#dns" id="id12">DNS</a></li>
<li><a class="reference internal" href="#working-with-pipes" id="id13">Working with pipes</a></li>
<li><a class="reference internal" href="#unix-signals" id="id14">Unix 信号</a></li>
<li><a class="reference internal" href="#executing-code-in-thread-or-process-pools" id="id15">Executing code in thread or process pools</a></li>
<li><a class="reference internal" href="#error-handling-api" id="id16">错误处理API</a></li>
<li><a class="reference internal" href="#enabling-debug-mode" id="id17">Enabling debug mode</a></li>
<li><a class="reference internal" href="#running-subprocesses" id="id18">Running Subprocesses</a></li>
</ul>
</div>
<div class="section" id="running-and-stopping-the-loop">
<h3><a class="toc-backref" href="#id2">Running and stopping the loop</a><a class="headerlink" href="#running-and-stopping-the-loop" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.run_until_complete">
<code class="descclassname">loop.</code><code class="descname">run_until_complete</code><span class="sig-paren">(</span><em>future</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_until_complete" title="永久链接至目标">¶</a></dt>
<dd><p>Run until the <em>future</em> (an instance of <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>) has
completed.</p>
<p>如果参数是 <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">coroutine object</span></a> ，将被隐式调度为 <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a> 来运行。</p>
<p>Return the Future's result or raise its exception.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.run_forever">
<code class="descclassname">loop.</code><code class="descname">run_forever</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_forever" title="永久链接至目标">¶</a></dt>
<dd><p>Run the event loop until <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> is called.</p>
<p>If <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> is called before <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code></a> is called,
the loop will poll the I/O selector once with a timeout of zero,
run all callbacks scheduled in response to I/O events (and
those that were already scheduled), and then exit.</p>
<p>If <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> is called while <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code></a> is running,
the loop will run the current batch of callbacks and then exit.
Note that new callbacks scheduled by callbacks will not run in this
case; instead, they will run the next time <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code></a> or
<a class="reference internal" href="#asyncio.loop.run_until_complete" title="asyncio.loop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_until_complete()</span></code></a> is called.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.stop">
<code class="descclassname">loop.</code><code class="descname">stop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.stop" title="永久链接至目标">¶</a></dt>
<dd><p>停止事件循环。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.is_running">
<code class="descclassname">loop.</code><code class="descname">is_running</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.is_running" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the event loop is currently running.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.is_closed">
<code class="descclassname">loop.</code><code class="descname">is_closed</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.is_closed" title="永久链接至目标">¶</a></dt>
<dd><p>如果事件循环已经被关闭，返回 <code class="docutils literal notranslate"><span class="pre">True</span></code> 。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.close">
<code class="descclassname">loop.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.close" title="永久链接至目标">¶</a></dt>
<dd><p>关闭事件循环。</p>
<p>The loop must not be running when this function is called.
Any pending callbacks will be discarded.</p>
<p>This method clears all queues and shuts down the executor, but does
not wait for the executor to finish.</p>
<p>This method is idempotent and irreversible.  No other methods
should be called after the event loop is closed.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.shutdown_asyncgens">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">shutdown_asyncgens</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.shutdown_asyncgens" title="永久链接至目标">¶</a></dt>
<dd><p>Schedule all currently open <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> objects to
close with an <a class="reference internal" href="../reference/expressions.html#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> call.  After calling this method,
the event loop will issue a warning if a new asynchronous generator
is iterated. This should be used to reliably finalize all scheduled
asynchronous generators.</p>
<p>Note that there is no need to call this function when
<a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> is used.</p>
<p>示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">shutdown_asyncgens</span><span class="p">())</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">3.6 新版功能.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="scheduling-callbacks">
<h3><a class="toc-backref" href="#id3">Scheduling callbacks</a><a class="headerlink" href="#scheduling-callbacks" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.call_soon">
<code class="descclassname">loop.</code><code class="descname">call_soon</code><span class="sig-paren">(</span><em>callback</em>, <em>*args</em>, <em>context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_soon" title="永久链接至目标">¶</a></dt>
<dd><p>Schedule a <em>callback</em> to be called with <em>args</em> arguments at
the next iteration of the event loop.</p>
<p>Callbacks are called in the order in which they are registered.
Each callback will be called exactly once.</p>
<p>An optional keyword-only <em>context</em> argument allows specifying a
custom <a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>callback</em> to run in.
The current context is used when no <em>context</em> is provided.</p>
<p>An instance of <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Handle</span></code></a> is returned, which can be
used later to cancel the callback.</p>
<p>这个方法不是线程安全的。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.call_soon_threadsafe">
<code class="descclassname">loop.</code><code class="descname">call_soon_threadsafe</code><span class="sig-paren">(</span><em>callback</em>, <em>*args</em>, <em>context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_soon_threadsafe" title="永久链接至目标">¶</a></dt>
<dd><p>A thread-safe variant of <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon()</span></code></a>.  Must be used to
schedule callbacks <em>from another thread</em>.</p>
<p>查看 <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">并发和多线程</span></a> 章节的文档。</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>仅用于关键字形参的参数  <em>context</em>  已经被添加。请参阅： <span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> 查看更多细节。</p>
</div>
<div class="admonition note" id="asyncio-pass-keywords">
<p class="first admonition-title">注解</p>
<p>Most <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> scheduling functions don't allow passing
keyword arguments.  To do that, use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># will schedule &quot;print(&quot;Hello&quot;, flush=True)&quot;</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span>
    <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Hello&quot;</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
</pre></div>
</div>
<p class="last">Using partial objects is usually more convenient than using lambdas,
as asyncio can render partial objects better in debug and error
messages.</p>
</div>
</div>
<div class="section" id="scheduling-delayed-callbacks">
<span id="asyncio-delayed-calls"></span><h3><a class="toc-backref" href="#id4">Scheduling delayed callbacks</a><a class="headerlink" href="#scheduling-delayed-callbacks" title="永久链接至标题">¶</a></h3>
<p>Event loop provides mechanisms to schedule callback functions
to be called at some point in the future.  Event loop uses monotonic
clocks to track time.</p>
<dl class="method">
<dt id="asyncio.loop.call_later">
<code class="descclassname">loop.</code><code class="descname">call_later</code><span class="sig-paren">(</span><em>delay</em>, <em>callback</em>, <em>*args</em>, <em>context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_later" title="永久链接至目标">¶</a></dt>
<dd><p>Schedule <em>callback</em> to be called after the given <em>delay</em>
number of seconds (can be either an int or a float).</p>
<p>返回一个 <a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TimerHandle</span></code></a> 实例，该实例能用于取消回调。</p>
<p><em>callback</em> will be called exactly once.  If two callbacks are
scheduled for exactly the same time, the order in which they
are called is undefined.</p>
<p>The optional positional <em>args</em> will be passed to the callback when
it is called. If you want the callback to be called with keyword
arguments use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a>.</p>
<p>An optional keyword-only <em>context</em> argument allows specifying a
custom <a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>callback</em> to run in.
The current context is used when no <em>context</em> is provided.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>仅用于关键字形参的参数  <em>context</em>  已经被添加。请参阅： <span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> 查看更多细节。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7.1 版更改: </span>In Python 3.7.0 and earlier with the default event loop implementation,
the <em>delay</em> could not exceed one day.
This has been fixed in Python 3.7.1.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.call_at">
<code class="descclassname">loop.</code><code class="descname">call_at</code><span class="sig-paren">(</span><em>when</em>, <em>callback</em>, <em>*args</em>, <em>context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_at" title="永久链接至目标">¶</a></dt>
<dd><p>Schedule <em>callback</em> to be called at the given absolute timestamp
<em>when</em> (an int or a float), using the same time reference as
<a class="reference internal" href="#asyncio.loop.time" title="asyncio.loop.time"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.time()</span></code></a>.</p>
<p>这个函数的行为与 <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_later()</span></code></a> 相同。</p>
<p>返回一个 <a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TimerHandle</span></code></a> 实例，该实例能用于取消回调。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>仅用于关键字形参的参数  <em>context</em>  已经被添加。请参阅： <span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> 查看更多细节。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7.1 版更改: </span>In Python 3.7.0 and earlier with the default event loop implementation,
the difference between <em>when</em> and the current time could not exceed
one day.  This has been fixed in Python 3.7.1.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.time">
<code class="descclassname">loop.</code><code class="descname">time</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.time" title="永久链接至目标">¶</a></dt>
<dd><p>Return the current time, as a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> value, according to
the event loop's internal monotonic clock.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">超时（相对 <em>delay</em> 或者绝对 <em>when</em> ）不能超过一天。</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference internal" href="asyncio-task.html#asyncio.sleep" title="asyncio.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.sleep()</span></code></a> 函数</p>
</div>
</div>
<div class="section" id="creating-futures-and-tasks">
<h3><a class="toc-backref" href="#id5">Creating Futures and Tasks</a><a class="headerlink" href="#creating-futures-and-tasks" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.create_future">
<code class="descclassname">loop.</code><code class="descname">create_future</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_future" title="永久链接至目标">¶</a></dt>
<dd><p>Create an <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> object attached to the event loop.</p>
<p>This is the preferred way to create Futures in asyncio. This lets
third-party event loops provide alternative implementations of
the Future object (with better performance or instrumentation).</p>
<div class="versionadded">
<p><span class="versionmodified">3.5.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.create_task">
<code class="descclassname">loop.</code><code class="descname">create_task</code><span class="sig-paren">(</span><em>coro</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_task" title="永久链接至目标">¶</a></dt>
<dd><p>Schedule the execution of a <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">协程</span></a>.
Return a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object.</p>
<p>三方的事件循环可以使用它们自己定义的 <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> 类的子类来实现互操作性。这个例子里，返回值的类型是 <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> 的子类。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.set_task_factory">
<code class="descclassname">loop.</code><code class="descname">set_task_factory</code><span class="sig-paren">(</span><em>factory</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_task_factory" title="永久链接至目标">¶</a></dt>
<dd><p>Set a task factory that will be used by
<a class="reference internal" href="#asyncio.loop.create_task" title="asyncio.loop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_task()</span></code></a>.</p>
<p>If <em>factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> the default task factory will be set.
Otherwise, <em>factory</em> must be a <em>callable</em> with the signature matching
<code class="docutils literal notranslate"><span class="pre">(loop,</span> <span class="pre">coro)</span></code>, where <em>loop</em> is a reference to the active
event loop, and <em>coro</em> is a coroutine object.  The callable
must return a <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a>-compatible object.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.get_task_factory">
<code class="descclassname">loop.</code><code class="descname">get_task_factory</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.get_task_factory" title="永久链接至目标">¶</a></dt>
<dd><p>Return a task factory or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the default one is in use.</p>
</dd></dl>

</div>
<div class="section" id="opening-network-connections">
<h3><a class="toc-backref" href="#id6">Opening network connections</a><a class="headerlink" href="#opening-network-connections" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.create_connection">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">create_connection</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>host=None</em>, <em>port=None</em>, <em>*</em>, <em>ssl=None</em>, <em>family=0</em>, <em>proto=0</em>, <em>flags=0</em>, <em>sock=None</em>, <em>local_addr=None</em>, <em>server_hostname=None</em>, <em>ssl_handshake_timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_connection" title="永久链接至目标">¶</a></dt>
<dd><p>Open a streaming transport connection to a given
address specified by <em>host</em> and <em>port</em>.</p>
<p>The socket family can be either <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET</span></code></a> or
<a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> depending on <em>host</em> (or the <em>family</em>
argument, if provided).</p>
<p>The socket type will be <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a>.</p>
<p><em>protocol_factory</em> must be a callable returning an
<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">asyncio protocol</span></a> implementation.</p>
<p>这个方法会尝试在后台创建连接。当创建成功，返回 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> 组合。</p>
<p>基本操作的时间顺序如下：</p>
<ol class="arabic simple">
<li>The connection is established and a <a class="reference internal" href="asyncio-protocol.html#asyncio-transport"><span class="std std-ref">transport</span></a>
is created for it.</li>
<li><em>protocol_factory</em> is called without arguments and is expected to
return a <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> instance.</li>
<li>The protocol instance is coupled with the transport by calling its
<a class="reference internal" href="asyncio-protocol.html#asyncio.BaseProtocol.connection_made" title="asyncio.BaseProtocol.connection_made"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connection_made()</span></code></a> method.</li>
<li>成功时返回一个 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> 元组。</li>
</ol>
<p>创建的transport是一个实现相关的双向流。</p>
<p>Other arguments:</p>
<ul>
<li><p class="first"><em>ssl</em>: if given and not false, a SSL/TLS transport is created
(by default a plain TCP transport is created).  If <em>ssl</em> is
a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> object, this context is used to create
the transport; if <em>ssl</em> is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, a default context returned
from <a class="reference internal" href="ssl.html#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.create_default_context()</span></code></a> is used.</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference internal" href="ssl.html#ssl-security"><span class="std std-ref">SSL/TLS安全事项</span></a></p>
</div>
</li>
<li><p class="first"><em>server_hostname</em> sets or overrides the hostname that the target
server's certificate will be matched against.  Should only be passed
if <em>ssl</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>.  By default the value of the <em>host</em> argument
is used.  If <em>host</em> is empty, there is no default and you must pass a
value for <em>server_hostname</em>.  If <em>server_hostname</em> is an empty
string, hostname matching is disabled (which is a serious security
risk, allowing for potential man-in-the-middle attacks).</p>
</li>
<li><p class="first"><em>family</em>，<em>proto</em>，<em>flags</em> 是可选的地址族，协议和标志，通过传递给 getaddrinfo() 来解析 <em>host</em>。如果给出，这些应该都是来自 <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> 模块相应的常量的整数。</p>
</li>
<li><p class="first"><em>sock</em>，如果给出的话，应该是一个现有的，已经连接的 <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a> 对象，这个对象将被transport使用。如果给出 <em>sock</em>，则 <em>host</em>，<em>port</em>，<em>family</em>，<em>proto</em>，<em>flags</em> 和 <em>local_addr</em> 中的任何一个都不应该指定。</p>
</li>
<li><p class="first"><em>local_addr</em>, if given, is a <code class="docutils literal notranslate"><span class="pre">(local_host,</span> <span class="pre">local_port)</span></code> tuple used
to bind the socket to locally.  The <em>local_host</em> and <em>local_port</em>
are looked up using <code class="docutils literal notranslate"><span class="pre">getaddrinfo()</span></code>, similarly to <em>host</em> and <em>port</em>.</p>
</li>
<li><p class="first"><em>ssl_handshake_timeout</em> is (for a TLS connection) the time in seconds
to wait for the TLS handshake to complete before aborting the connection.
<code class="docutils literal notranslate"><span class="pre">60.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</p>
</li>
</ul>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能: </span><em>ssl_handshake_timeout</em> 形参。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.6 版更改: </span>The socket option <code class="xref py py-data docutils literal notranslate"><span class="pre">TCP_NODELAY</span></code> is set by default
for all TCP connections.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5 版更改: </span>Added support for SSL/TLS in <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a>.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">The <a class="reference internal" href="asyncio-stream.html#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_connection()</span></code></a> function is a high-level alternative
API.  It returns a pair of (<a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>, <a class="reference internal" href="asyncio-stream.html#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a>)
that can be used directly in async/await code.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.create_datagram_endpoint">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">create_datagram_endpoint</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>local_addr=None</em>, <em>remote_addr=None</em>, <em>*</em>, <em>family=0</em>, <em>proto=0</em>, <em>flags=0</em>, <em>reuse_address=None</em>, <em>reuse_port=None</em>, <em>allow_broadcast=None</em>, <em>sock=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_datagram_endpoint" title="永久链接至目标">¶</a></dt>
<dd><p>创建一个数据报连接。</p>
<p>The socket family can be either <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET</span></code></a>,
<a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>, or <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>,
depending on <em>host</em> (or the <em>family</em> argument, if provided).</p>
<p>socket类型将是 <a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_DGRAM</span></code></a> 。</p>
<p><em>protocol_factory</em> must be a callable returning a
<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</p>
<p>A tuple of <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> is returned on success.</p>
<p>Other arguments:</p>
<ul class="simple">
<li><em>local_addr</em>，如果指定的话，就是一个 <code class="docutils literal notranslate"><span class="pre">(local_host,</span> <span class="pre">local_port)</span></code> 元组，用于在本地绑定套接字。 <em>local_host</em> 和 <em>local_port</em> 是使用 <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> 来查找的。</li>
<li><em>remote_addr</em>，如果指定的话，就是一个 <code class="docutils literal notranslate"><span class="pre">(remote_host,</span> <span class="pre">remote_port)</span></code> 元组，用于同一个远程地址连接。<em>remote_host</em> 和 <em>remote_port</em> 是使用 <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> 来查找的。</li>
<li><em>family</em>, <em>proto</em>, <em>flags</em> 是可选的地址族，协议和标志，其会被传递给 <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> 来完成 <em>host</em> 的解析。如果要指定的话，这些都应该是来自于 <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> 模块的对应常量。</li>
<li><em>reuse_address</em> tells the kernel to reuse a local socket in
<code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code> state, without waiting for its natural timeout to
expire. If not specified will automatically be set to <code class="docutils literal notranslate"><span class="pre">True</span></code> on
Unix.</li>
<li><em>reuse_port</em> tells the kernel to allow this endpoint to be bound to the
same port as other existing endpoints are bound to, so long as they all
set this flag when being created. This option is not supported on Windows
and some Unixes. If the <code class="xref py py-data docutils literal notranslate"><span class="pre">SO_REUSEPORT</span></code> constant is not
defined then this capability is unsupported.</li>
<li><em>allow_broadcast</em> 告知内核允许此端点向广播地址发送消息。</li>
<li><em>sock</em> 可选择通过指定此值用于使用一个预先存在的，已经处于连接状态的 <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a> 对象，并将其提供给此传输对象使用。如果指定了这个值， <em>local_addr</em> 和 <em>remote_addr</em> 就应该被忽略 (必须为 <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>)。</li>
</ul>
<p>On Windows, with <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a>, this method is not supported.</p>
<p>参见 <a class="reference internal" href="asyncio-protocol.html#asyncio-udp-echo-client-protocol"><span class="std std-ref">UDP echo 客户端协议</span></a>  和 <a class="reference internal" href="asyncio-protocol.html#asyncio-udp-echo-server-protocol"><span class="std std-ref">UDP echo 服务端协议</span></a> 的例子。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.4.4 版更改: </span>添加了 <em>family</em>, <em>proto</em>, <em>flags</em>, <em>reuse_address</em>, <em>reuse_port</em>, <em>allow_broadcast</em> 和 <em>sock</em> 等参数。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.create_unix_connection">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">create_unix_connection</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>path=None</em>, <em>*</em>, <em>ssl=None</em>, <em>sock=None</em>, <em>server_hostname=None</em>, <em>ssl_handshake_timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_unix_connection" title="永久链接至目标">¶</a></dt>
<dd><p>Create a Unix connection.</p>
<p>The socket family will be <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>; socket
type will be <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a>.</p>
<p>A tuple of <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> is returned on success.</p>
<p><em>path</em> is the name of a Unix domain socket and is required,
unless a <em>sock</em> parameter is specified.  Abstract Unix sockets,
<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, and <a class="reference internal" href="pathlib.html#pathlib.Path" title="pathlib.Path"><code class="xref py py-class docutils literal notranslate"><span class="pre">Path</span></code></a> paths are
supported.</p>
<p>See the documentation of the <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> method
for information about arguments to this method.</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能: </span><em>ssl_handshake_timeout</em> 形参。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span><em>path</em> 形参现在可以是 <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a> 对象。</p>
</div>
</dd></dl>

</div>
<div class="section" id="creating-network-servers">
<h3><a class="toc-backref" href="#id7">Creating network servers</a><a class="headerlink" href="#creating-network-servers" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.create_server">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">create_server</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>host=None</em>, <em>port=None</em>, <em>*</em>, <em>family=socket.AF_UNSPEC</em>, <em>flags=socket.AI_PASSIVE</em>, <em>sock=None</em>, <em>backlog=100</em>, <em>ssl=None</em>, <em>reuse_address=None</em>, <em>reuse_port=None</em>, <em>ssl_handshake_timeout=None</em>, <em>start_serving=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_server" title="永久链接至目标">¶</a></dt>
<dd><p>Create a TCP server (socket type <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a>) listening
on <em>port</em> of the <em>host</em> address.</p>
<p>Returns a <a class="reference internal" href="#asyncio.Server" title="asyncio.Server"><code class="xref py py-class docutils literal notranslate"><span class="pre">Server</span></code></a> object.</p>
<p>Arguments:</p>
<ul class="simple">
<li><em>protocol_factory</em> must be a callable returning a
<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</li>
<li>The <em>host</em> parameter can be set to several types which determine where
the server would be listening:<ul>
<li>If <em>host</em> is a string, the TCP server is bound to a single network
interface specified by <em>host</em>.</li>
<li>If <em>host</em> is a sequence of strings, the TCP server is bound to all
network interfaces specified by the sequence.</li>
<li>If <em>host</em> is an empty string or <code class="docutils literal notranslate"><span class="pre">None</span></code>, all interfaces are
assumed and a list of multiple sockets will be returned (most likely
one for IPv4 and another one for IPv6).</li>
</ul>
</li>
<li><em>family</em> can be set to either <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">socket.AF_INET</span></code></a> or
<a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> to force the socket to use IPv4 or IPv6.
If not set, the <em>family</em> will be determined from host name
(defaults to <code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNSPEC</span></code>).</li>
<li><em>flags</em> 是用于 <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> 的位掩码。</li>
<li><em>sock</em> can optionally be specified in order to use a preexisting
socket object. If specified, <em>host</em> and <em>port</em> must not be specified.</li>
<li><em>backlog</em> 是传递给 <a class="reference internal" href="socket.html#socket.socket.listen" title="socket.socket.listen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code></a> 的最大排队连接的数量（默认为100）。</li>
<li><em>ssl</em> can be set to an <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> instance to enable
TLS over the accepted connections.</li>
<li><em>reuse_address</em> tells the kernel to reuse a local socket in
<code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code> state, without waiting for its natural timeout to
expire. If not specified will automatically be set to <code class="docutils literal notranslate"><span class="pre">True</span></code> on
Unix.</li>
<li><em>reuse_port</em> 告知内核，只要在创建的时候都设置了这个标志，就允许此端点绑定到其它端点列表所绑定的同样的端口上。这个选项在 Windows 上是不支持的。</li>
<li><em>ssl_handshake_timeout</em> is (for a TLS server) the time in seconds to wait
for the TLS handshake to complete before aborting the connection.
<code class="docutils literal notranslate"><span class="pre">60.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</li>
<li><em>start_serving</em> 设置成 <code class="docutils literal notranslate"><span class="pre">True</span></code> (默认值) 会导致创建server并立即开始接受连接。设置成 <code class="docutils literal notranslate"><span class="pre">False</span></code> ，用户需要等待 <a class="reference internal" href="#asyncio.Server.start_serving" title="asyncio.Server.start_serving"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Server.start_serving()</span></code></a> 或者 <a class="reference internal" href="#asyncio.Server.serve_forever" title="asyncio.Server.serve_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Server.serve_forever()</span></code></a> 以使server开始接受连接。</li>
</ul>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能: </span>Added <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.6 版更改: </span>The socket option <code class="xref py py-data docutils literal notranslate"><span class="pre">TCP_NODELAY</span></code> is set by default
for all TCP connections.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5 版更改: </span>Added support for SSL/TLS in <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5.1 版更改: </span>The <em>host</em> parameter can be a sequence of strings.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">The <a class="reference internal" href="asyncio-stream.html#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a> function is a higher-level alternative API
that returns a pair of <a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="asyncio-stream.html#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a>
that can be used in an async/await code.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.create_unix_server">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">create_unix_server</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>path=None</em>, <em>*</em>, <em>sock=None</em>, <em>backlog=100</em>, <em>ssl=None</em>, <em>ssl_handshake_timeout=None</em>, <em>start_serving=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_unix_server" title="永久链接至目标">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a> but works with the
<a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> socket family.</p>
<p><em>path</em> is the name of a Unix domain socket, and is required,
unless a <em>sock</em> argument is provided.  Abstract Unix sockets,
<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, and <a class="reference internal" href="pathlib.html#pathlib.Path" title="pathlib.Path"><code class="xref py py-class docutils literal notranslate"><span class="pre">Path</span></code></a> paths
are supported.</p>
<p>See the documentation of the <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a> method
for information about arguments to this method.</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能: </span>The <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span><em>path</em> 形参现在可以是 <a class="reference internal" href="pathlib.html#pathlib.Path" title="pathlib.Path"><code class="xref py py-class docutils literal notranslate"><span class="pre">Path</span></code></a> 对象。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.connect_accepted_socket">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">connect_accepted_socket</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>sock</em>, <em>*</em>, <em>ssl=None</em>, <em>ssl_handshake_timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.connect_accepted_socket" title="永久链接至目标">¶</a></dt>
<dd><p>Wrap an already accepted connection into a transport/protocol pair.</p>
<p>This method can be used by servers that accept connections outside
of asyncio but that use asyncio to handle them.</p>
<p>参数：</p>
<ul class="simple">
<li><em>protocol_factory</em> must be a callable returning a
<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</li>
<li><em>sock</em> is a preexisting socket object returned from
<a class="reference internal" href="socket.html#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.accept</span></code></a>.</li>
<li><em>ssl</em> 可被设置为一个 <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> 以在接受的连接上启用 SSL。</li>
<li><em>ssl_handshake_timeout</em> 是(为一个SSL连接)在中止连接前，等待SSL握手完成的时间【单位秒】。如果为 <code class="docutils literal notranslate"><span class="pre">None</span></code> (缺省) 则是 <code class="docutils literal notranslate"><span class="pre">60.0</span></code> 秒。</li>
</ul>
<p>Returns a <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> pair.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能: </span><em>ssl_handshake_timeout</em> 形参。</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">3.5.3 新版功能.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="transferring-files">
<h3><a class="toc-backref" href="#id8">传输文件</a><a class="headerlink" href="#transferring-files" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.sendfile">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">sendfile</code><span class="sig-paren">(</span><em>transport</em>, <em>file</em>, <em>offset=0</em>, <em>count=None</em>, <em>*</em>, <em>fallback=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sendfile" title="永久链接至目标">¶</a></dt>
<dd><p>Send a <em>file</em> over a <em>transport</em>.  Return the total number of bytes
sent.</p>
<p>如果可用的化，该方法将使用高性能的 <a class="reference internal" href="os.html#os.sendfile" title="os.sendfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">os.sendfile()</span></code></a> 。</p>
<p><em>file</em> 必须是个二进制模式打开的常规文件对象。</p>
<p><em>offset</em> tells from where to start reading the file. If specified,
<em>count</em> is the total number of bytes to transmit as opposed to
sending the file until EOF is reached. File position is always updated,
even when this method raises an error, and
<a class="reference internal" href="io.html#io.IOBase.tell" title="io.IOBase.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.tell()</span></code></a> can be used to obtain the actual
number of bytes sent.</p>
<p><em>fallback</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code> makes asyncio to manually read and send
the file when the platform does not support the sendfile system call
(e.g. Windows or SSL socket on Unix).</p>
<p>Raise <a class="reference internal" href="asyncio-exceptions.html#asyncio.SendfileNotAvailableError" title="asyncio.SendfileNotAvailableError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SendfileNotAvailableError</span></code></a> if the system does not support
the <em>sendfile</em> syscall and <em>fallback</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="tls-upgrade">
<h3><a class="toc-backref" href="#id9">TLS 升级</a><a class="headerlink" href="#tls-upgrade" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.start_tls">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">start_tls</code><span class="sig-paren">(</span><em>transport</em>, <em>protocol</em>, <em>sslcontext</em>, <em>*</em>, <em>server_side=False</em>, <em>server_hostname=None</em>, <em>ssl_handshake_timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.start_tls" title="永久链接至目标">¶</a></dt>
<dd><p>Upgrade an existing transport-based connection to TLS.</p>
<p>Return a new transport instance, that the <em>protocol</em> must start using
immediately after the <em>await</em>.  The <em>transport</em> instance passed to
the <em>start_tls</em> method should never be used again.</p>
<p>参数：</p>
<ul class="simple">
<li><em>transport</em> and <em>protocol</em> instances that methods like
<a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_server()</span></code></a> and
<a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_connection()</span></code></a> return.</li>
<li><em>sslcontext</em> ：一个已经配置好的 <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> 实例。</li>
<li><em>server_side</em> pass <code class="docutils literal notranslate"><span class="pre">True</span></code> when a server-side connection is being
upgraded (like the one created by <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_server()</span></code></a>).</li>
<li><em>server_hostname</em> ：设置或者覆盖目标服务器证书中相对应的主机名。</li>
<li><em>ssl_handshake_timeout</em> is (for a TLS connection) the time in seconds to
wait for the TLS handshake to complete before aborting the connection.
<code class="docutils literal notranslate"><span class="pre">60.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</li>
</ul>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="watching-file-descriptors">
<h3><a class="toc-backref" href="#id10">Watching file descriptors</a><a class="headerlink" href="#watching-file-descriptors" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.add_reader">
<code class="descclassname">loop.</code><code class="descname">add_reader</code><span class="sig-paren">(</span><em>fd</em>, <em>callback</em>, <em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_reader" title="永久链接至目标">¶</a></dt>
<dd><p>Start monitoring the <em>fd</em> file descriptor for read availability and
invoke <em>callback</em> with the specified arguments once <em>fd</em> is available for
reading.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.remove_reader">
<code class="descclassname">loop.</code><code class="descname">remove_reader</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_reader" title="永久链接至目标">¶</a></dt>
<dd><p>Stop monitoring the <em>fd</em> file descriptor for read availability.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.add_writer">
<code class="descclassname">loop.</code><code class="descname">add_writer</code><span class="sig-paren">(</span><em>fd</em>, <em>callback</em>, <em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_writer" title="永久链接至目标">¶</a></dt>
<dd><p>Start monitoring the <em>fd</em> file descriptor for write availability and
invoke <em>callback</em> with the specified arguments once <em>fd</em> is available for
writing.</p>
<p>Use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> <a class="reference internal" href="#asyncio-pass-keywords"><span class="std std-ref">to pass keyword arguments</span></a> to <em>callback</em>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.remove_writer">
<code class="descclassname">loop.</code><code class="descname">remove_writer</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_writer" title="永久链接至目标">¶</a></dt>
<dd><p>Stop monitoring the <em>fd</em> file descriptor for write availability.</p>
</dd></dl>

<p>See also <a class="reference internal" href="asyncio-platforms.html#asyncio-platform-support"><span class="std std-ref">Platform Support</span></a> section
for some limitations of these methods.</p>
</div>
<div class="section" id="working-with-socket-objects-directly">
<h3><a class="toc-backref" href="#id11">Working with socket objects directly</a><a class="headerlink" href="#working-with-socket-objects-directly" title="永久链接至标题">¶</a></h3>
<p>In general, protocol implementations that use transport-based APIs
such as <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> and <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a>
are faster than implementations that work with sockets directly.
However, there are some use cases when performance is not critical, and
working with <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> objects directly is more
convenient.</p>
<dl class="method">
<dt id="asyncio.loop.sock_recv">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">sock_recv</code><span class="sig-paren">(</span><em>sock</em>, <em>nbytes</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_recv" title="永久链接至目标">¶</a></dt>
<dd><p>Receive up to <em>nbytes</em> from <em>sock</em>.  Asynchronous version of
<a class="reference internal" href="socket.html#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.recv()</span></code></a>.</p>
<p>返回接收到的数据【bytes对象类型】。</p>
<p><em>sock</em> must be a non-blocking socket.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>Even though this method was always documented as a coroutine
method, releases before Python 3.7 returned a <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>.
Since Python 3.7 this is an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> method.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.sock_recv_into">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">sock_recv_into</code><span class="sig-paren">(</span><em>sock</em>, <em>buf</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_recv_into" title="永久链接至目标">¶</a></dt>
<dd><p>Receive data from <em>sock</em> into the <em>buf</em> buffer.  Modeled after the blocking
<a class="reference internal" href="socket.html#socket.socket.recv_into" title="socket.socket.recv_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.recv_into()</span></code></a> method.</p>
<p>Return the number of bytes written to the buffer.</p>
<p><em>sock</em> must be a non-blocking socket.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.sock_sendall">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">sock_sendall</code><span class="sig-paren">(</span><em>sock</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_sendall" title="永久链接至目标">¶</a></dt>
<dd><p>Send <em>data</em> to the <em>sock</em> socket. Asynchronous version of
<a class="reference internal" href="socket.html#socket.socket.sendall" title="socket.socket.sendall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.sendall()</span></code></a>.</p>
<p>This method continues to send to the socket until either all data
in <em>data</em> has been sent or an error occurs.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned
on success.  On error, an exception is raised. Additionally, there is no way
to determine how much data, if any, was successfully processed by the
receiving end of the connection.</p>
<p><em>sock</em> must be a non-blocking socket.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>虽然这个方法一直被标记为协程方法。但是，Python 3.7 之前，该方法返回 <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> ，从Python 3.7 开始，这个方法是 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> 方法。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.sock_connect">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">sock_connect</code><span class="sig-paren">(</span><em>sock</em>, <em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_connect" title="永久链接至目标">¶</a></dt>
<dd><p>Connect <em>sock</em> to a remote socket at <em>address</em>.</p>
<p>Asynchronous version of <a class="reference internal" href="socket.html#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.connect()</span></code></a>.</p>
<p><em>sock</em> must be a non-blocking socket.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5.2 版更改: </span><code class="docutils literal notranslate"><span class="pre">address</span></code> no longer needs to be resolved.  <code class="docutils literal notranslate"><span class="pre">sock_connect</span></code>
will try to check if the <em>address</em> is already resolved by calling
<a class="reference internal" href="socket.html#socket.inet_pton" title="socket.inet_pton"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket.inet_pton()</span></code></a>.  If not,
<a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.getaddrinfo()</span></code></a> will be used to resolve the
<em>address</em>.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> 和  <a class="reference internal" href="asyncio-stream.html#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.open_connection()</span></code></a> 。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.sock_accept">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">sock_accept</code><span class="sig-paren">(</span><em>sock</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_accept" title="永久链接至目标">¶</a></dt>
<dd><p>Accept a connection.  Modeled after the blocking
<a class="reference internal" href="socket.html#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.accept()</span></code></a> method.</p>
<p>此 <em>scoket</em> 必须绑定到一个地址上并且监听连接。返回值是一个 <code class="docutils literal notranslate"><span class="pre">(conn,</span> <span class="pre">address)</span></code> 对，其中 <em>conn</em> 是一个 <em>新*的套接字对象，用于在此连接上收发数据，*address</em> 是连接的另一端的套接字所绑定的地址。</p>
<p><em>sock</em> must be a non-blocking socket.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>虽然这个方法一直被标记为协程方法。但是，Python 3.7 之前，该方法返回 <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> ，从Python 3.7 开始，这个方法是 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> 方法。</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a> and <a class="reference internal" href="asyncio-stream.html#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.sock_sendfile">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">sock_sendfile</code><span class="sig-paren">(</span><em>sock</em>, <em>file</em>, <em>offset=0</em>, <em>count=None</em>, <em>*</em>, <em>fallback=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_sendfile" title="永久链接至目标">¶</a></dt>
<dd><p>Send a file using high-performance <a class="reference internal" href="os.html#os.sendfile" title="os.sendfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.sendfile</span></code></a> if possible.
Return the total number of bytes sent.</p>
<p>Asynchronous version of <a class="reference internal" href="socket.html#socket.socket.sendfile" title="socket.socket.sendfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.sendfile()</span></code></a>.</p>
<p><em>sock</em> must be a non-blocking <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_STREAM</span></code></a>
<a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a>.</p>
<p><em>file</em> must be a regular file object open in binary mode.</p>
<p><em>offset</em> tells from where to start reading the file. If specified,
<em>count</em> is the total number of bytes to transmit as opposed to
sending the file until EOF is reached. File position is always updated,
even when this method raises an error, and
<a class="reference internal" href="io.html#io.IOBase.tell" title="io.IOBase.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.tell()</span></code></a> can be used to obtain the actual
number of bytes sent.</p>
<p><em>fallback</em>, when set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, makes asyncio manually read and send
the file when the platform does not support the sendfile syscall
(e.g. Windows or SSL socket on Unix).</p>
<p>如果系统不支持 <em>sendfile</em> 并且 <em>fallback</em> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> ，引发 <a class="reference internal" href="asyncio-exceptions.html#asyncio.SendfileNotAvailableError" title="asyncio.SendfileNotAvailableError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SendfileNotAvailableError</span></code></a> 异常。</p>
<p><em>sock</em> must be a non-blocking socket.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="dns">
<h3><a class="toc-backref" href="#id12">DNS</a><a class="headerlink" href="#dns" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.getaddrinfo">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">getaddrinfo</code><span class="sig-paren">(</span><em>host</em>, <em>port</em>, <em>*</em>, <em>family=0</em>, <em>type=0</em>, <em>proto=0</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.getaddrinfo" title="永久链接至目标">¶</a></dt>
<dd><p>Asynchronous version of <a class="reference internal" href="socket.html#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.getaddrinfo()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.getnameinfo">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">getnameinfo</code><span class="sig-paren">(</span><em>sockaddr</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.getnameinfo" title="永久链接至目标">¶</a></dt>
<dd><p>Asynchronous version of <a class="reference internal" href="socket.html#socket.getnameinfo" title="socket.getnameinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.getnameinfo()</span></code></a>.</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span><em>getaddrinfo</em> 和 <em>getnameinfo</em> 方法一直被标记返回一个协程，但是Python 3.7之前，实际返回的是 <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> 对象。从Python 3.7 开始，这两个方法是协程。</p>
</div>
</div>
<div class="section" id="working-with-pipes">
<h3><a class="toc-backref" href="#id13">Working with pipes</a><a class="headerlink" href="#working-with-pipes" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.connect_read_pipe">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">connect_read_pipe</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>pipe</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.connect_read_pipe" title="永久链接至目标">¶</a></dt>
<dd><p>Register the read end of <em>pipe</em> in the event loop.</p>
<p><em>protocol_factory</em> must be a callable returning an
<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">asyncio protocol</span></a> implementation.</p>
<p><em>pipe</em> is a <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file-like object</span></a>.</p>
<p>Return pair <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>, where <em>transport</em> supports
the <a class="reference internal" href="asyncio-protocol.html#asyncio.ReadTransport" title="asyncio.ReadTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">ReadTransport</span></code></a> interface and <em>protocol</em> is an object
instantiated by the <em>protocol_factory</em>.</p>
<p>使用 <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> 事件循环， <em>pipe</em> 被设置为非阻塞模式。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.connect_write_pipe">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">connect_write_pipe</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>pipe</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.connect_write_pipe" title="永久链接至目标">¶</a></dt>
<dd><p>Register the write end of <em>pipe</em> in the event loop.</p>
<p><em>protocol_factory</em> must be a callable returning an
<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">asyncio protocol</span></a> implementation.</p>
<p><em>pipe</em> is <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file-like object</span></a>.</p>
<p>Return pair <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>, where <em>transport</em> supports
<a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport" title="asyncio.WriteTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">WriteTransport</span></code></a> interface and <em>protocol</em> is an object
instantiated by the <em>protocol_factory</em>.</p>
<p>使用 <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> 事件循环， <em>pipe</em> 被设置为非阻塞模式。</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last"><a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> does not support the above methods on
Windows.  Use <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> instead for Windows.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">The <a class="reference internal" href="#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_exec()</span></code></a> and
<a class="reference internal" href="#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_shell()</span></code></a> methods.</p>
</div>
</div>
<div class="section" id="unix-signals">
<h3><a class="toc-backref" href="#id14">Unix 信号</a><a class="headerlink" href="#unix-signals" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.add_signal_handler">
<code class="descclassname">loop.</code><code class="descname">add_signal_handler</code><span class="sig-paren">(</span><em>signum</em>, <em>callback</em>, <em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_signal_handler" title="永久链接至目标">¶</a></dt>
<dd><p>Set <em>callback</em> as the handler for the <em>signum</em> signal.</p>
<p>The callback will be invoked by <em>loop</em>, along with other queued callbacks
and runnable coroutines of that event loop. Unlike signal handlers
registered using <a class="reference internal" href="signal.html#signal.signal" title="signal.signal"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.signal()</span></code></a>, a callback registered with this
function is allowed to interact with the event loop.</p>
<p>如果信号数字非法或者不可捕获，就抛出一个 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> 。如果建立处理器的过程中出现问题，会抛出一个 <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> 。</p>
<p>Use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> <a class="reference internal" href="#asyncio-pass-keywords"><span class="std std-ref">to pass keyword arguments</span></a> to <em>callback</em>.</p>
<p>Like <a class="reference internal" href="signal.html#signal.signal" title="signal.signal"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.signal()</span></code></a>, this function must be invoked in the main
thread.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.remove_signal_handler">
<code class="descclassname">loop.</code><code class="descname">remove_signal_handler</code><span class="sig-paren">(</span><em>sig</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_signal_handler" title="永久链接至目标">¶</a></dt>
<dd><p>Remove the handler for the <em>sig</em> signal.</p>
<p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the signal handler was removed, or <code class="docutils literal notranslate"><span class="pre">False</span></code> if
no handler was set for the given signal.</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> 模块。</p>
</div>
</div>
<div class="section" id="executing-code-in-thread-or-process-pools">
<h3><a class="toc-backref" href="#id15">Executing code in thread or process pools</a><a class="headerlink" href="#executing-code-in-thread-or-process-pools" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.run_in_executor">
<em class="property">awaitable </em><code class="descclassname">loop.</code><code class="descname">run_in_executor</code><span class="sig-paren">(</span><em>executor</em>, <em>func</em>, <em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_in_executor" title="永久链接至目标">¶</a></dt>
<dd><p>Arrange for <em>func</em> to be called in the specified executor.</p>
<p>The <em>executor</em> argument should be an <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Executor" title="concurrent.futures.Executor"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Executor</span></code></a>
instance. The default executor is used if <em>executor</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">concurrent.futures</span>

<span class="k">def</span> <span class="nf">blocking_io</span><span class="p">():</span>
    <span class="c1"># File operations (such as logging) can block the</span>
    <span class="c1"># event loop: run them in a thread pool.</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/dev/urandom&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">cpu_bound</span><span class="p">():</span>
    <span class="c1"># CPU-bound operations will block the event loop:</span>
    <span class="c1"># in general it is preferable to run them in a</span>
    <span class="c1"># process pool.</span>
    <span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">i</span> <span class="o">*</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span> <span class="o">**</span> <span class="mi">7</span><span class="p">))</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_running_loop</span><span class="p">()</span>

    <span class="c1">## Options:</span>

    <span class="c1"># 1. Run in the default loop&#39;s executor:</span>
    <span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_in_executor</span><span class="p">(</span>
        <span class="kc">None</span><span class="p">,</span> <span class="n">blocking_io</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;default thread pool&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>

    <span class="c1"># 2. Run in a custom thread pool:</span>
    <span class="k">with</span> <span class="n">concurrent</span><span class="o">.</span><span class="n">futures</span><span class="o">.</span><span class="n">ThreadPoolExecutor</span><span class="p">()</span> <span class="k">as</span> <span class="n">pool</span><span class="p">:</span>
        <span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_in_executor</span><span class="p">(</span>
            <span class="n">pool</span><span class="p">,</span> <span class="n">blocking_io</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;custom thread pool&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>

    <span class="c1"># 3. Run in a custom process pool:</span>
    <span class="k">with</span> <span class="n">concurrent</span><span class="o">.</span><span class="n">futures</span><span class="o">.</span><span class="n">ProcessPoolExecutor</span><span class="p">()</span> <span class="k">as</span> <span class="n">pool</span><span class="p">:</span>
        <span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_in_executor</span><span class="p">(</span>
            <span class="n">pool</span><span class="p">,</span> <span class="n">cpu_bound</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;custom process pool&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>

<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
</pre></div>
</div>
<p>这个方法返回一个 <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> 对象。</p>
<p>Use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> <a class="reference internal" href="#asyncio-pass-keywords"><span class="std std-ref">to pass keyword arguments</span></a> to <em>func</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.5.3 版更改: </span><a class="reference internal" href="#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.run_in_executor()</span></code></a> no longer configures the
<code class="docutils literal notranslate"><span class="pre">max_workers</span></code> of the thread pool executor it creates, instead
leaving it up to the thread pool executor
(<a class="reference internal" href="concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadPoolExecutor</span></code></a>) to set the
default.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.set_default_executor">
<code class="descclassname">loop.</code><code class="descname">set_default_executor</code><span class="sig-paren">(</span><em>executor</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_default_executor" title="永久链接至目标">¶</a></dt>
<dd><p>Set <em>executor</em> as the default executor used by <a class="reference internal" href="#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_in_executor()</span></code></a>.
<em>executor</em> should be an instance of
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadPoolExecutor</span></code></a>.</p>
<div class="deprecated">
<p><span class="versionmodified">3.7 版后已移除: </span>Using an executor that is not an instance of
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadPoolExecutor</span></code></a> is deprecated and
will trigger an error in Python 3.9.</p>
</div>
<p><em>executor</em> must be an instance of
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.ThreadPoolExecutor</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="error-handling-api">
<h3><a class="toc-backref" href="#id16">错误处理API</a><a class="headerlink" href="#error-handling-api" title="永久链接至标题">¶</a></h3>
<p>允许自定义事件循环中如何去处理异常。</p>
<dl class="method">
<dt id="asyncio.loop.set_exception_handler">
<code class="descclassname">loop.</code><code class="descname">set_exception_handler</code><span class="sig-paren">(</span><em>handler</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_exception_handler" title="永久链接至目标">¶</a></dt>
<dd><p>将 <em>handler</em> 设置为新的事件循环异常处理器。</p>
<p>If <em>handler</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the default exception handler will
be set.  Otherwise, <em>handler</em> must be a callable with the signature
matching <code class="docutils literal notranslate"><span class="pre">(loop,</span> <span class="pre">context)</span></code>, where <code class="docutils literal notranslate"><span class="pre">loop</span></code>
is a reference to the active event loop, and <code class="docutils literal notranslate"><span class="pre">context</span></code>
is a <code class="docutils literal notranslate"><span class="pre">dict</span></code> object containing the details of the exception
(see <a class="reference internal" href="#asyncio.loop.call_exception_handler" title="asyncio.loop.call_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_exception_handler()</span></code></a> documentation for details
about context).</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.get_exception_handler">
<code class="descclassname">loop.</code><code class="descname">get_exception_handler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.get_exception_handler" title="永久链接至目标">¶</a></dt>
<dd><p>Return the current exception handler, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no custom
exception handler was set.</p>
<div class="versionadded">
<p><span class="versionmodified">3.5.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.default_exception_handler">
<code class="descclassname">loop.</code><code class="descname">default_exception_handler</code><span class="sig-paren">(</span><em>context</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.default_exception_handler" title="永久链接至目标">¶</a></dt>
<dd><p>默认的异常处理器。</p>
<p>This is called when an exception occurs and no exception
handler is set. This can be called by a custom exception
handler that wants to defer to the default handler behavior.</p>
<p><em>context</em> 参数和 <a class="reference internal" href="#asyncio.loop.call_exception_handler" title="asyncio.loop.call_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_exception_handler()</span></code></a> 中的同名参数完全相同。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.call_exception_handler">
<code class="descclassname">loop.</code><code class="descname">call_exception_handler</code><span class="sig-paren">(</span><em>context</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_exception_handler" title="永久链接至目标">¶</a></dt>
<dd><p>调用当前事件循环异常处理器。</p>
<p><em>context</em> 是个包含下列键的 <code class="docutils literal notranslate"><span class="pre">dict</span></code> 对象(未来版本的Python可能会引入新键)：</p>
<ul class="simple">
<li>'message': 错误消息；</li>
<li>'exception' （可选）: 异常对象；</li>
<li>'future' （可选）:  <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> 实例。</li>
<li>'handle' （可选）: <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Handle</span></code></a> 实例；</li>
<li>'protocol' （可选）: <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">Protocol</span></a> 实例；</li>
<li>'transport' （可选）: <a class="reference internal" href="asyncio-protocol.html#asyncio-transport"><span class="std std-ref">Transport</span></a> 实例；</li>
<li>'socket' （可选）： <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a> 实例。</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">This method should not be overloaded in subclassed
event loops.  For custom exception handling, use
the <a class="reference internal" href="#asyncio.loop.set_exception_handler" title="asyncio.loop.set_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception_handler()</span></code></a> method.</p>
</div>
</dd></dl>

</div>
<div class="section" id="enabling-debug-mode">
<h3><a class="toc-backref" href="#id17">Enabling debug mode</a><a class="headerlink" href="#enabling-debug-mode" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="asyncio.loop.get_debug">
<code class="descclassname">loop.</code><code class="descname">get_debug</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.get_debug" title="永久链接至目标">¶</a></dt>
<dd><p>获取事件循环调试模式状态（<a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>）。</p>
<p>如果环境变量 <span class="target" id="index-11"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONASYNCIODEBUG"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONASYNCIODEBUG</span></code></a> 是一个非空字符串，就返回 <code class="docutils literal notranslate"><span class="pre">True</span></code> ，否则就返回 <code class="docutils literal notranslate"><span class="pre">False</span></code> 。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.set_debug">
<code class="descclassname">loop.</code><code class="descname">set_debug</code><span class="sig-paren">(</span><em>enabled: bool</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_debug" title="永久链接至目标">¶</a></dt>
<dd><p>设置事件循环的调试模式。</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>The new <code class="docutils literal notranslate"><span class="pre">-X</span> <span class="pre">dev</span></code> command line option can now also be used
to enable the debug mode.</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">debug mode of asyncio</span></a>.</p>
</div>
</div>
<div class="section" id="running-subprocesses">
<h3><a class="toc-backref" href="#id18">Running Subprocesses</a><a class="headerlink" href="#running-subprocesses" title="永久链接至标题">¶</a></h3>
<p>Methods described in this subsections are low-level.  In regular
async/await code consider using the high-level
<a class="reference internal" href="asyncio-subprocess.html#asyncio.create_subprocess_shell" title="asyncio.create_subprocess_shell"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_subprocess_shell()</span></code></a> and
<a class="reference internal" href="asyncio-subprocess.html#asyncio.create_subprocess_exec" title="asyncio.create_subprocess_exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_subprocess_exec()</span></code></a> convenience functions instead.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">The default asyncio event loop on <strong>Windows</strong> does not support
subprocesses. See <a class="reference internal" href="asyncio-platforms.html#asyncio-windows-subprocess"><span class="std std-ref">Subprocess Support on Windows</span></a> for details.</p>
</div>
<dl class="method">
<dt id="asyncio.loop.subprocess_exec">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">subprocess_exec</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>*args</em>, <em>stdin=subprocess.PIPE</em>, <em>stdout=subprocess.PIPE</em>, <em>stderr=subprocess.PIPE</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.subprocess_exec" title="永久链接至目标">¶</a></dt>
<dd><p>Create a subprocess from one or more string arguments specified by
<em>args</em>.</p>
<p><em>args</em> must be a list of strings represented by:</p>
<ul class="simple">
<li><a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>;</li>
<li>or <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, encoded to the
<a class="reference internal" href="os.html#filesystem-encoding"><span class="std std-ref">filesystem encoding</span></a>.</li>
</ul>
<p>The first string specifies the program executable,
and the remaining strings specify the arguments.  Together, string
arguments form the <code class="docutils literal notranslate"><span class="pre">argv</span></code> of the program.</p>
<p>This is similar to the standard library <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a>
class called with <code class="docutils literal notranslate"><span class="pre">shell=False</span></code> and the list of strings passed as
the first argument; however, where <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> takes
a single argument which is list of strings, <em>subprocess_exec</em>
takes multiple string arguments.</p>
<p>The <em>protocol_factory</em> must be a callable returning a subclass of the
<a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol" title="asyncio.SubprocessProtocol"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.SubprocessProtocol</span></code></a> class.</p>
<p>Other parameters:</p>
<ul>
<li><p class="first"><em>stdin</em>: either a file-like object representing a pipe to be
connected to the subprocess's standard input stream using
<a class="reference internal" href="#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_write_pipe()</span></code></a>, or the
<a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a>  constant (default). By default a new
pipe will be created and connected.</p>
</li>
<li><p class="first"><em>stdout</em>: either a file-like object representing the pipe to be
connected to the subprocess's standard output stream using
<a class="reference internal" href="#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_read_pipe()</span></code></a>, or the
<a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a> constant (default). By default a new pipe
will be created and connected.</p>
</li>
<li><p class="first"><em>stderr</em>: either a file-like object representing the pipe to be
connected to the subprocess's standard error stream using
<a class="reference internal" href="#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_read_pipe()</span></code></a>, or one of
<a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a> (default) or <a class="reference internal" href="subprocess.html#subprocess.STDOUT" title="subprocess.STDOUT"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.STDOUT</span></code></a>
constants.</p>
<p>By default a new pipe will be created and connected. When
<a class="reference internal" href="subprocess.html#subprocess.STDOUT" title="subprocess.STDOUT"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.STDOUT</span></code></a> is specified, the subprocess' standard
error stream will be connected to the same pipe as the standard
output stream.</p>
</li>
<li><p class="first">All other keyword arguments are passed to <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a>
without interpretation, except for <em>bufsize</em>, <em>universal_newlines</em>
and <em>shell</em>, which should not be specified at all.</p>
</li>
</ul>
<p>See the constructor of the <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a> class
for documentation on other arguments.</p>
<p>Returns a pair of <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>, where <em>transport</em>
conforms to the <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport" title="asyncio.SubprocessTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.SubprocessTransport</span></code></a> base class and
<em>protocol</em> is an object instantiated by the <em>protocol_factory</em>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.loop.subprocess_shell">
<em class="property">coroutine </em><code class="descclassname">loop.</code><code class="descname">subprocess_shell</code><span class="sig-paren">(</span><em>protocol_factory</em>, <em>cmd</em>, <em>*</em>, <em>stdin=subprocess.PIPE</em>, <em>stdout=subprocess.PIPE</em>, <em>stderr=subprocess.PIPE</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.subprocess_shell" title="永久链接至目标">¶</a></dt>
<dd><p>Create a subprocess from <em>cmd</em>, which can be a <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or a
<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> string encoded to the
<a class="reference internal" href="os.html#filesystem-encoding"><span class="std std-ref">filesystem encoding</span></a>,
using the platform's &quot;shell&quot; syntax.</p>
<p>这类似与用 <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> 调用标准库的 <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a> 类。</p>
<p>The <em>protocol_factory</em> must be a callable returning a subclass of the
<a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol" title="asyncio.SubprocessProtocol"><code class="xref py py-class docutils literal notranslate"><span class="pre">SubprocessProtocol</span></code></a> class.</p>
<p>See <a class="reference internal" href="#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subprocess_exec()</span></code></a> for more details about
the remaining arguments.</p>
<p>Returns a pair of <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>, where <em>transport</em>
conforms to the <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport" title="asyncio.SubprocessTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">SubprocessTransport</span></code></a> base class and
<em>protocol</em> is an object instantiated by the <em>protocol_factory</em>.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">It is the application's responsibility to ensure that all whitespace
and special characters are quoted appropriately to avoid <a class="reference external" href="https://en.wikipedia.org/wiki/Shell_injection#Shell_injection">shell injection</a>
vulnerabilities. The <a class="reference internal" href="shlex.html#shlex.quote" title="shlex.quote"><code class="xref py py-func docutils literal notranslate"><span class="pre">shlex.quote()</span></code></a> function can be used to
properly escape whitespace and special characters in strings that
are going to be used to construct shell commands.</p>
</div>
</div>
</div>
<div class="section" id="callback-handles">
<h2>Callback Handles<a class="headerlink" href="#callback-handles" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="asyncio.Handle">
<em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">Handle</code><a class="headerlink" href="#asyncio.Handle" title="永久链接至目标">¶</a></dt>
<dd><p>A callback wrapper object returned by <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a>,
<a class="reference internal" href="#asyncio.loop.call_soon_threadsafe" title="asyncio.loop.call_soon_threadsafe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon_threadsafe()</span></code></a>.</p>
<dl class="method">
<dt id="asyncio.Handle.cancel">
<code class="descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Handle.cancel" title="永久链接至目标">¶</a></dt>
<dd><p>Cancel the callback.  If the callback has already been canceled
or executed, this method has no effect.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Handle.cancelled">
<code class="descname">cancelled</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Handle.cancelled" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the callback was cancelled.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="asyncio.TimerHandle">
<em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">TimerHandle</code><a class="headerlink" href="#asyncio.TimerHandle" title="永久链接至目标">¶</a></dt>
<dd><p>A callback wrapper object returned by <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_later()</span></code></a>,
and <a class="reference internal" href="#asyncio.loop.call_at" title="asyncio.loop.call_at"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_at()</span></code></a>.</p>
<p>This class is a subclass of <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code class="xref py py-class docutils literal notranslate"><span class="pre">Handle</span></code></a>.</p>
<dl class="method">
<dt id="asyncio.TimerHandle.when">
<code class="descname">when</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.TimerHandle.when" title="永久链接至目标">¶</a></dt>
<dd><p>Return a scheduled callback time as <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> seconds.</p>
<p>The time is an absolute timestamp, using the same time
reference as <a class="reference internal" href="#asyncio.loop.time" title="asyncio.loop.time"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.time()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="server-objects">
<h2>Server Objects<a class="headerlink" href="#server-objects" title="永久链接至标题">¶</a></h2>
<p>Server objects are created by <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a>,
<a class="reference internal" href="#asyncio.loop.create_unix_server" title="asyncio.loop.create_unix_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_server()</span></code></a>, <a class="reference internal" href="asyncio-stream.html#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a>,
and <a class="reference internal" href="asyncio-stream.html#asyncio.start_unix_server" title="asyncio.start_unix_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_unix_server()</span></code></a> functions.</p>
<p>Do not instantiate the class directly.</p>
<dl class="class">
<dt id="asyncio.Server">
<em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">Server</code><a class="headerlink" href="#asyncio.Server" title="永久链接至目标">¶</a></dt>
<dd><p><em>Server</em> 对象是异步上下文管理器。当用于 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> 语句时，异步上下文管理器可以确保 Server 对象被关闭，并且在 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> 语句完成后，不接受新的连接。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">srv</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">create_server</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>

<span class="k">async</span> <span class="k">with</span> <span class="n">srv</span><span class="p">:</span>
    <span class="c1"># some code</span>

<span class="c1"># At this point, srv is closed and no longer accepts new connections.</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>Python3.7 开始，Server 对象是一个异步上下文管理器。</p>
</div>
<dl class="method">
<dt id="asyncio.Server.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.close" title="永久链接至目标">¶</a></dt>
<dd><p>停止服务：关闭监听的套接字并且设置 <a class="reference internal" href="#asyncio.Server.sockets" title="asyncio.Server.sockets"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sockets</span></code></a> 属性为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 。</p>
<p>用于表示已经连进来的客户端连接会保持打开的状态。</p>
<p>服务器是被异步关闭的，使用 <a class="reference internal" href="#asyncio.Server.wait_closed" title="asyncio.Server.wait_closed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait_closed()</span></code></a> 协程来等待服务器关闭。</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Server.get_loop">
<code class="descname">get_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.get_loop" title="永久链接至目标">¶</a></dt>
<dd><p>Return the event loop associated with the server object.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.Server.start_serving">
<em class="property">coroutine </em><code class="descname">start_serving</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.start_serving" title="永久链接至目标">¶</a></dt>
<dd><p>开始接受连接。</p>
<p>这个方法是幂等的【相同参数重复执行，能获得相同的结果】，所以此方法能在服务已经运行的时候调用。</p>
<p>The <em>start_serving</em> keyword-only parameter to
<a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a> and
<a class="reference internal" href="asyncio-stream.html#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.start_server()</span></code></a> allows creating a Server object
that is not accepting connections initially.  In this case
<code class="docutils literal notranslate"><span class="pre">Server.start_serving()</span></code>, or <a class="reference internal" href="#asyncio.Server.serve_forever" title="asyncio.Server.serve_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Server.serve_forever()</span></code></a> can be used
to make the Server start accepting connections.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.Server.serve_forever">
<em class="property">coroutine </em><code class="descname">serve_forever</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.serve_forever" title="永久链接至目标">¶</a></dt>
<dd><p>开始接受连接，直到协程被取消。 <code class="docutils literal notranslate"><span class="pre">serve_forever</span></code> 任务的取消将导致服务器被关闭。</p>
<p>如果服务器已经在接受连接了，这个方法可以被调用。每个 <em>Server</em> 对象，仅能有一个 <code class="docutils literal notranslate"><span class="pre">serve_forever</span></code> 任务。</p>
<p>示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">client_connected</span><span class="p">(</span><span class="n">reader</span><span class="p">,</span> <span class="n">writer</span><span class="p">):</span>
    <span class="c1"># Communicate with the client with</span>
    <span class="c1"># reader/writer streams.  For example:</span>
    <span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">):</span>
    <span class="n">srv</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">start_server</span><span class="p">(</span>
        <span class="n">client_connected</span><span class="p">,</span> <span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">)</span>
    <span class="k">await</span> <span class="n">srv</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>

<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">(</span><span class="s1">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.Server.is_serving">
<code class="descname">is_serving</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.is_serving" title="永久链接至目标">¶</a></dt>
<dd><p>如果服务器正在接受新连接的状态，返回 <code class="docutils literal notranslate"><span class="pre">True</span></code> 。</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncio.Server.wait_closed">
<em class="property">coroutine </em><code class="descname">wait_closed</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.wait_closed" title="永久链接至目标">¶</a></dt>
<dd><p>等待 <a class="reference internal" href="#asyncio.Server.close" title="asyncio.Server.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 方法执行完毕。</p>
</dd></dl>

<dl class="attribute">
<dt id="asyncio.Server.sockets">
<code class="descname">sockets</code><a class="headerlink" href="#asyncio.Server.sockets" title="永久链接至目标">¶</a></dt>
<dd><p>List of <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a> objects the server is listening on,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the server is closed.</p>
<div class="versionchanged">
<p><span class="versionmodified">在 3.7 版更改: </span>Prior to Python 3.7 <code class="docutils literal notranslate"><span class="pre">Server.sockets</span></code> used to return an
internal list of server sockets directly.  In 3.7 a copy
of that list is returned.</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="event-loop-implementations">
<span id="asyncio-event-loops"></span><h2>Event Loop Implementations<a class="headerlink" href="#event-loop-implementations" title="永久链接至标题">¶</a></h2>
<p>asyncio ships with two different event loop implementations:
<a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> and <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a>.</p>
<p>By default asyncio is configured to use <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a>
on all platforms.</p>
<dl class="class">
<dt id="asyncio.SelectorEventLoop">
<em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">SelectorEventLoop</code><a class="headerlink" href="#asyncio.SelectorEventLoop" title="永久链接至目标">¶</a></dt>
<dd><p>An event loop based on the <a class="reference internal" href="selectors.html#module-selectors" title="selectors: High-level I/O multiplexing."><code class="xref py py-mod docutils literal notranslate"><span class="pre">selectors</span></code></a> module.</p>
<p>Uses the most efficient <em>selector</em> available for the given
platform.  It is also possible to manually configure the
exact selector implementation to be used:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">selectors</span>

<span class="n">selector</span> <span class="o">=</span> <span class="n">selectors</span><span class="o">.</span><span class="n">SelectSelector</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">SelectorEventLoop</span><span class="p">(</span><span class="n">selector</span><span class="p">)</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">set_event_loop</span><span class="p">(</span><span class="n">loop</span><span class="p">)</span>
</pre></div>
</div>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix, Windows。</p>
</dd></dl>

<dl class="class">
<dt id="asyncio.ProactorEventLoop">
<em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">ProactorEventLoop</code><a class="headerlink" href="#asyncio.ProactorEventLoop" title="永久链接至目标">¶</a></dt>
<dd><p>用 &quot;I/O Completion Ports&quot; (IOCP) 构建的专为Windows 的事件循环。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows.</p>
<p>An example how to use <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> on Windows:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span> <span class="o">==</span> <span class="s1">&#39;win32&#39;</span><span class="p">:</span>
    <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">ProactorEventLoop</span><span class="p">()</span>
    <span class="n">asyncio</span><span class="o">.</span><span class="n">set_event_loop</span><span class="p">(</span><span class="n">loop</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference external" href="https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports">MSDN documentation on I/O Completion Ports</a>.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="asyncio.AbstractEventLoop">
<em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">AbstractEventLoop</code><a class="headerlink" href="#asyncio.AbstractEventLoop" title="永久链接至目标">¶</a></dt>
<dd><p>Abstract base class for asyncio-compliant event loops.</p>
<p>The <a class="reference internal" href="#asyncio-event-loop"><span class="std std-ref">Event Loop Methods</span></a> section lists all
methods that an alternative implementation of <code class="docutils literal notranslate"><span class="pre">AbstractEventLoop</span></code>
should have defined.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<h2>示例<a class="headerlink" href="#examples" title="永久链接至标题">¶</a></h2>
<p>Note that all examples in this section <strong>purposefully</strong> show how
to use the low-level event loop APIs, such as <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.run_forever()</span></code></a>
and <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a>.  Modern asyncio applications rarely
need to be written this way; consider using the high-level functions
like <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a>.</p>
<div class="section" id="hello-world-with-call-soon">
<span id="asyncio-example-lowlevel-helloworld"></span><h3>call_soon() 的 Hello World 示例。<a class="headerlink" href="#hello-world-with-call-soon" title="永久链接至标题">¶</a></h3>
<p>An example using the <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a> method to schedule a
callback. The callback displays <code class="docutils literal notranslate"><span class="pre">&quot;Hello</span> <span class="pre">World&quot;</span></code> and then stops the
event loop:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="k">def</span> <span class="nf">hello_world</span><span class="p">(</span><span class="n">loop</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;A callback to print &#39;Hello World&#39; and stop the event loop&quot;&quot;&quot;</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello World&#39;</span><span class="p">)</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>

<span class="c1"># Schedule a call to hello_world()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span><span class="n">hello_world</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>

<span class="c1"># Blocking call interrupted by loop.stop()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">A similar <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">Hello World</span></a>
example created with a coroutine and the <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a> function.</p>
</div>
</div>
<div class="section" id="display-the-current-date-with-call-later">
<span id="asyncio-example-call-later"></span><h3>使用 call_later() 来展示当前的日期<a class="headerlink" href="#display-the-current-date-with-call-later" title="永久链接至标题">¶</a></h3>
<p>An example of a callback displaying the current date every second. The
callback uses the <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_later()</span></code></a> method to reschedule itself
after 5 seconds, and then stops the event loop:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">datetime</span>

<span class="k">def</span> <span class="nf">display_date</span><span class="p">(</span><span class="n">end_time</span><span class="p">,</span> <span class="n">loop</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">1.0</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">end_time</span><span class="p">:</span>
        <span class="n">loop</span><span class="o">.</span><span class="n">call_later</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">display_date</span><span class="p">,</span> <span class="n">end_time</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>

<span class="c1"># Schedule the first call to display_date()</span>
<span class="n">end_time</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">5.0</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span><span class="n">display_date</span><span class="p">,</span> <span class="n">end_time</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>

<span class="c1"># Blocking call interrupted by loop.stop()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">A similar <a class="reference internal" href="asyncio-task.html#asyncio-example-sleep"><span class="std std-ref">current date</span></a> example
created with a coroutine and the <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a> function.</p>
</div>
</div>
<div class="section" id="watch-a-file-descriptor-for-read-events">
<span id="asyncio-example-watch-fd"></span><h3>监控一个文件描述符的读事件<a class="headerlink" href="#watch-a-file-descriptor-for-read-events" title="永久链接至标题">¶</a></h3>
<p>使用 <a class="reference internal" href="#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_reader()</span></code></a> 方法，等到文件描述符收到一些数据，然后关闭事件循环：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">from</span> <span class="nn">socket</span> <span class="k">import</span> <span class="n">socketpair</span>

<span class="c1"># Create a pair of connected file descriptors</span>
<span class="n">rsock</span><span class="p">,</span> <span class="n">wsock</span> <span class="o">=</span> <span class="n">socketpair</span><span class="p">()</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">reader</span><span class="p">():</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">rsock</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Received:&quot;</span><span class="p">,</span> <span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">())</span>

    <span class="c1"># We are done: unregister the file descriptor</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">remove_reader</span><span class="p">(</span><span class="n">rsock</span><span class="p">)</span>

    <span class="c1"># Stop the event loop</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>

<span class="c1"># Register the file descriptor for read event</span>
<span class="n">loop</span><span class="o">.</span><span class="n">add_reader</span><span class="p">(</span><span class="n">rsock</span><span class="p">,</span> <span class="n">reader</span><span class="p">)</span>

<span class="c1"># Simulate the reception of data from the network</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span><span class="n">wsock</span><span class="o">.</span><span class="n">send</span><span class="p">,</span> <span class="s1">&#39;abc&#39;</span><span class="o">.</span><span class="n">encode</span><span class="p">())</span>

<span class="k">try</span><span class="p">:</span>
    <span class="c1"># Run the event loop</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="c1"># We are done. Close sockets and the event loop.</span>
    <span class="n">rsock</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="n">wsock</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<ul class="last simple">
<li>A similar <a class="reference internal" href="asyncio-protocol.html#asyncio-example-create-connection"><span class="std std-ref">example</span></a>
using transports, protocols, and the
<a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> method.</li>
<li>Another similar <a class="reference internal" href="asyncio-stream.html#asyncio-example-create-connection-streams"><span class="std std-ref">example</span></a>
using the high-level <a class="reference internal" href="asyncio-stream.html#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.open_connection()</span></code></a> function
and streams.</li>
</ul>
</div>
</div>
<div class="section" id="set-signal-handlers-for-sigint-and-sigterm">
<span id="asyncio-example-unix-signals"></span><h3>为SIGINT和SIGTERM设置信号处理器<a class="headerlink" href="#set-signal-handlers-for-sigint-and-sigterm" title="永久链接至标题">¶</a></h3>
<p>(This <code class="docutils literal notranslate"><span class="pre">signals</span></code> example only works on Unix.)</p>
<p>Register handlers for signals <code class="xref py py-data docutils literal notranslate"><span class="pre">SIGINT</span></code> and <code class="xref py py-data docutils literal notranslate"><span class="pre">SIGTERM</span></code>
using the <a class="reference internal" href="#asyncio.loop.add_signal_handler" title="asyncio.loop.add_signal_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_signal_handler()</span></code></a> method:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">functools</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">signal</span>

<span class="k">def</span> <span class="nf">ask_exit</span><span class="p">(</span><span class="n">signame</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;got signal </span><span class="si">%s</span><span class="s2">: exit&quot;</span> <span class="o">%</span> <span class="n">signame</span><span class="p">)</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_running_loop</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">signame</span> <span class="ow">in</span> <span class="p">{</span><span class="s1">&#39;SIGINT&#39;</span><span class="p">,</span> <span class="s1">&#39;SIGTERM&#39;</span><span class="p">}:</span>
        <span class="n">loop</span><span class="o">.</span><span class="n">add_signal_handler</span><span class="p">(</span>
            <span class="nb">getattr</span><span class="p">(</span><span class="n">signal</span><span class="p">,</span> <span class="n">signame</span><span class="p">),</span>
            <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">ask_exit</span><span class="p">,</span> <span class="n">signame</span><span class="p">))</span>

    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">3600</span><span class="p">)</span>

<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Event loop running for 1 hour, press Ctrl+C to interrupt.&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="s2">&quot;pid {os.getpid()}: send SIGINT or SIGTERM to exit.&quot;</span><span class="p">)</span>

<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">事件循环</a><ul>
<li><a class="reference internal" href="#event-loop-methods">事件循环方法集</a><ul>
<li><a class="reference internal" href="#running-and-stopping-the-loop">Running and stopping the loop</a></li>
<li><a class="reference internal" href="#scheduling-callbacks">Scheduling callbacks</a></li>
<li><a class="reference internal" href="#scheduling-delayed-callbacks">Scheduling delayed callbacks</a></li>
<li><a class="reference internal" href="#creating-futures-and-tasks">Creating Futures and Tasks</a></li>
<li><a class="reference internal" href="#opening-network-connections">Opening network connections</a></li>
<li><a class="reference internal" href="#creating-network-servers">Creating network servers</a></li>
<li><a class="reference internal" href="#transferring-files">传输文件</a></li>
<li><a class="reference internal" href="#tls-upgrade">TLS 升级</a></li>
<li><a class="reference internal" href="#watching-file-descriptors">Watching file descriptors</a></li>
<li><a class="reference internal" href="#working-with-socket-objects-directly">Working with socket objects directly</a></li>
<li><a class="reference internal" href="#dns">DNS</a></li>
<li><a class="reference internal" href="#working-with-pipes">Working with pipes</a></li>
<li><a class="reference internal" href="#unix-signals">Unix 信号</a></li>
<li><a class="reference internal" href="#executing-code-in-thread-or-process-pools">Executing code in thread or process pools</a></li>
<li><a class="reference internal" href="#error-handling-api">错误处理API</a></li>
<li><a class="reference internal" href="#enabling-debug-mode">Enabling debug mode</a></li>
<li><a class="reference internal" href="#running-subprocesses">Running Subprocesses</a></li>
</ul>
</li>
<li><a class="reference internal" href="#callback-handles">Callback Handles</a></li>
<li><a class="reference internal" href="#server-objects">Server Objects</a></li>
<li><a class="reference internal" href="#event-loop-implementations">Event Loop Implementations</a></li>
<li><a class="reference internal" href="#examples">示例</a><ul>
<li><a class="reference internal" href="#hello-world-with-call-soon">call_soon() 的 Hello World 示例。</a></li>
<li><a class="reference internal" href="#display-the-current-date-with-call-later">使用 call_later() 来展示当前的日期</a></li>
<li><a class="reference internal" href="#watch-a-file-descriptor-for-read-events">监控一个文件描述符的读事件</a></li>
<li><a class="reference internal" href="#set-signal-handlers-for-sigint-and-sigterm">为SIGINT和SIGTERM设置信号处理器</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="asyncio-exceptions.html"
                        title="上一章">异常</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="asyncio-future.html"
                        title="下一章">Futures</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/asyncio-eventloop.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="asyncio-future.html" title="Futures"
             >下一页</a> |</li>
        <li class="right" >
          <a href="asyncio-exceptions.html" title="异常"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">zh_CN</span>
          <span class="version_switcher_placeholder">3.7.3</span>
          <a href="../index.html">文档</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >网络和进程间通信</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="asyncio.html" ><code class="docutils literal notranslate"><span class="pre">asyncio</span></code> --- 异步 I/O</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2019, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 4月 09, 2019.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>1.8.4 创建。
    </div>

  </body>
</html>